package com.wx.activitys.drp.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.github.sd4324530.fastweixin.api.JsAPI;
import com.github.sd4324530.fastweixin.api.OauthAPI;
import com.github.sd4324530.fastweixin.api.enums.OauthScope;
import com.github.sd4324530.fastweixin.api.response.GetSignatureResponse;
import com.github.sd4324530.fastweixin.api.response.GetUserInfoResponse;
import com.github.sd4324530.fastweixin.api.response.OauthGetTokenResponse;
import com.wx.activitys.base.controller.BaseController;
import com.wx.activitys.base.utils.Common;
import com.wx.activitys.drp.barcode.ImageMarkLogoByIcon;
import com.wx.activitys.drp.barcode.QRCodeUtil;
import com.wx.activitys.drp.model.BUserInfo;
import com.wx.activitys.drp.service.UserInfoService;

@Controller
@RequestMapping(value = "/enCode")
public class EnCodeController extends BaseController {
	@Autowired
	private OauthAPI authAPI;
	@Autowired
	private JsAPI jsAPI;
	@Autowired
	private UserInfoService userInfoService;
	public static final String ROOT_NAME = "drp";
	public static final String BASE_PATH = "http://jh.xuanzhen-tech.com";
	public static final String BASE_URL = BASE_PATH;
	public static final String REDIRECT_URL = BASE_URL + "/enCode/dealAuthUser.html";

	@RequestMapping(value = "auth2.html", method = RequestMethod.GET)
	public void auth2(HttpSession session, HttpServletResponse response, HttpServletRequest request)
			throws IOException {
		String redirectURL = authAPI.getOauthPageUrl(REDIRECT_URL, OauthScope.SNSAPI_USERINFO, "STATE");
		response.sendRedirect(redirectURL);
	}

	@RequestMapping(value = "dealAuthUser.html", method = RequestMethod.GET)
	public String dealAuthUser(HttpSession session, HttpServletRequest request) {
		String code = request.getParameter("code");
		OauthGetTokenResponse authToken = authAPI.getToken(code);
		GetUserInfoResponse userInfo = authAPI.getUserInfo(authToken.getAccessToken(), authToken.getOpenid());
		//GetUserInfoResponse userInfo1 = userAPI.getUserInfo(authToken.getOpenid());
		logger.info("openid为" + authToken.getOpenid());
		logger.info(userInfo);
		session.setAttribute("userInfo", userInfo);
		return ROOT_NAME + "/codeRedirect";
	}

	@RequestMapping(value = "index.html", method = RequestMethod.GET)
	public String index(Model model, HttpServletRequest request, HttpServletResponse response,HttpSession session) {
		GetUserInfoResponse userInfo = ((GetUserInfoResponse) request.getSession().getAttribute("userInfo"));
		String onOpenId=request.getParameter("onOpenId");
		if (userInfo != null) {
				String currentPage = BASE_URL + "/enCode/index.html";
				GetSignatureResponse signObj = jsAPI.getSignature(currentPage);
				model.addAttribute("signObj", signObj);
				model.addAttribute("basePath", BASE_PATH);
				BUserInfo bUserInfo = userInfoService.findByOpenid(userInfo.getOpenid());
				if(bUserInfo!=null){
					if (StringUtils.isBlank(bUserInfo.getCodeImgUrl())) {
						String text = "http://jh.xuanzhen-tech.com/enter/auth2.html?onOpenId="+userInfo.getOpenid();
						String codeV = "";
						String srcImgPath = Common.IMG_SAVE_BASEPATH + "tui2.jpg";
						String code = "";
						Map<String, Object> map = new HashMap<>();
						try {
							String path = Common.IMG_SAVE_BASEPATH + "qrcode/";
							String imgUrl=bUserInfo.getHeadImgUrl();
							//String strUrl="http://wx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTLlk8ibibibyz8RAFuqu1h6Hiawd3icSKqzV1KfibtGhCfuic8sqIWFKvhDWdtApK88hmWIEibMRnNGFjsyhg/0";
							QRCodeUtil.writeFile(path, imgUrl);
							// 生成二维码
							codeV = QRCodeUtil.encode(text,path+"head.jpg",path);
							// 给图片添加水印
							String iconPath = path + codeV;
							code = ImageMarkLogoByIcon.markImageByIcon(iconPath, srcImgPath, path);
							map.put("openid", bUserInfo.getOpenid());
							map.put("codeImgUrl", "qrcode/" + code);
							userInfoService.update(map);
							model.addAttribute("url", "qrcode/"+code);
							model.addAttribute("onOpenId", userInfo.getOpenid());
						} catch (Exception e) {
							e.printStackTrace();
						}
					} else {
						model.addAttribute("onOpenId", userInfo.getOpenid());
						model.addAttribute("url", bUserInfo.getCodeImgUrl());
					}
					return "drp/user/share2";
				}else{
					return  "redirect:/enCenter/auth2.html?onOpenId="+onOpenId;
				}
		} else {
			 return "redirect:/enCode/auth2.html";
		}
	}
}
